package com.leo.ktvplayer.pay.wechat;


import android.os.Message;
import android.util.Log;

import com.leo.ktvplayer.localcookie.LocalUtils;
import com.leo.ktvplayer.pay.BasePaymentThread;
import com.leo.ktvplayer.pay.alipay.HttpsUtil;
import com.leo.ktvplayer.util.JsonUtil;
import com.leo.ktvplayer.util.Md5Util;
import com.leo.ktvplayer.util.RandomStrUtils;
import com.leo.ktvplayer.util.Xml2ByteUtils;
import com.leo.ktvplayer.util.XmlFormatUtil;

import java.io.IOException;
import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.XMLFormatter;

/**
 * Created by LeoLu on 2017/2/27.
 */
public class WechatPayment extends BasePaymentThread {

    private String wechatToken;
    private TreeMap<String  ,String > map = new TreeMap<>();
    private String TEST_ID = "wx02aba40cdf4145e4";
    private String TEST_MCH_ID = "1219121901";
    private String TEST_KEY = "eNbOFfWbOZuJ3ijkH30UJF9AVJHdRRI2";

    private void compassMap(){
            map.put("appid", LocalUtils.getUser().getWechat_appid());
            map.put("mch_id",LocalUtils.getUser().getWechat_mchid());
            map.put("nonce_str", RandomStrUtils.getRedomStr(32));
            map.put("out_trade_no",orderId);
            map.put("body","kty娱乐");
            map.put("spbill_create_ip","192.168.1.1");
            map.put("total_fee" , ((int)(money) * 100) + "");//微信的单价是分
            map.put("trade_type","NATIVE");
            map.put("notify_url","http://www.weixin.qq.com/wxpay/pay.php");
            signData(map);
            byte[] data = Xml2ByteUtils.callMapToXML(map);
        try {
            String result = HttpsUtil.doPost("https://api.mch.weixin.qq.com/pay/unifiedorder","text/xml;charset=UTF-8",data,10000,10000);

            WechatPayRespone respone =  XmlFormatUtil.xmlToObj(result,WechatPayRespone.class);
            Message message = Message.obtain();
            message.what = ON_URL_CALL;
            message.obj = respone.getCode_url();
            handler.sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public synchronized void start() {
        super.start();
    }

    private void signData(Map<String , String> map) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0 ; i < map.size(); i++) {
            Object[] keyarry = map.keySet().toArray();
            builder.append(keyarry[i] + "=" + map.get(keyarry[i]) +"&");
        }
        builder.append("key=" + LocalUtils.getUser().getWechat_key());
        String sign =  Md5Util.encryptToHex(builder.toString());
        map.put("sign",sign);

    }

    /**
     * 轮训微信服务器 做支付功能
     * @throws IOException
     */
    private void QueryMap() throws IOException {
        map.clear();
        map.put("appid",TEST_ID);
        map.put("mch_id",TEST_MCH_ID);
        map.put("out_trade_no",orderId);
        map.put("nonce_str",RandomStrUtils.getRedomStr(32));
        signData(map);
        byte[] data = Xml2ByteUtils.callMapToXML(map);
        String result = HttpsUtil.doPost("https://api.mch.weixin.qq.com/pay/orderquery","text/xml;charset=UTF-8",data,10000,10000);
        if(result.contains("transaction_id")) {
            WechatQueryRespone respone = XmlFormatUtil.xmlToObj(result,WechatQueryRespone.class);
            if (respone.getTrade_state().equals("SUCCESS")){
                handler.sendEmptyMessage(ON_SUCCESS);
            }
        }
    }

    @Override
    public void run() {
        super.run();
        compassMap();
        try {
            Thread.sleep(1000);
            while(isrunning) {
                QueryMap();
                Thread.sleep(2000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
